package com.cloud.base.thread.cas;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class TestDemoAtomic {
    Lock lock = new Lock();

    public TestDemoAtomic(int i) {
        lock.state = i;
    }

    public Integer addAndGet(int offset) throws Exception {
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);
        // 2.获取到unsafe
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        // 1.获取域的偏移地址
        long idOffset = unsafe.objectFieldOffset(Lock.class.getDeclaredField("state"));

        //死循环容易cpu标高，CAS中lock.state是与相知相当于V
        while (true) {
            //当Lock对象的state  等于compareAndSwapInt第三个字段时，将第四个字段赋值给Lock对象的state
            if (unsafe.compareAndSwapInt(lock, idOffset, lock.state, lock.state + offset)) {
                return lock.state;
            }
        }
    }

    public Integer get() {
        return lock.state;
    }

    static class Lock {
        int state;
    }

    public static void main(String[] args) throws Exception {
        TestDemoAtomic testDemoAtomic = new TestDemoAtomic(10);
        Integer integer = testDemoAtomic.addAndGet(20);
        System.out.println(integer);
    }
}
